package com.fb;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.StateListDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.dev.FileBrowserTab;
import com.dev.GUI;
import com.dev.IconViewClose;
import com.dev.MainActivity;
import com.dev.ShowSoftInput;
import com.dev.TabBar;
import com.dev.TabData;
import com.dev.UnderlineSingleLineEditor;
import java.io.File;
import com.dev.FileClipData;
import com.dev.ShowFileDetails;
class FileNavigator extends HorizontalScrollView implements OnClickListener,OnLongClickListener {
	LinearLayout main;
	FileBrowserPage fbp;
	FileNavigator(FileBrowserPage fbp){
		super(fbp.ma);
		this.fbp=fbp;
		MainActivity ma=fbp.ma;
		setFillViewport(true);
		setHorizontalScrollBarEnabled(false);
		main=new LinearLayout(ma){
			@Override
			protected void onLayout(boolean changed, int l, int t, int r, int b) {
				super.onLayout(changed, l, t, r, b);
				FileNavigator.this.setScrollX(getRight());
			}
		};
		main.setOrientation(LinearLayout.HORIZONTAL);
		addView(main);
	}
	void setPath(File f){
		File root=new File("/");
		main.removeAllViews();
		Tab t=new Tab(f);
		t.dest=f;
		main.addView(t,0);
		File parent=f.getParentFile();
		while(parent!=null){
			t=new Tab(parent);
			t.dest=parent;
			if(parent.equals(root)){
				t.setText("/");
			}
			main.addView(t,0);
			parent=parent.getParentFile();
		}

	}
	@Override
	public void onClick(View v){
		Tab t=(Tab)v;
		if(t.dest.canRead()){
			if(t.dest.equals(fbp.currentDirectory)){
				fbp.dlv.invalidate();
				Toast.makeText(fbp.ma,"已刷新",0).show();
			}else{
                long stamp=System.currentTimeMillis();
                //log.schedule();
				fbp.backable.push(fbp.currentDirectory);
				fbp.currentDirectory=t.dest;
				setPath(t.dest);
				File list[]=t.dest.listFiles();
                long now=System.currentTimeMillis();
                long gap=now-stamp;
                if(gap>1000l){
                    Toast toast=Toast.makeText(fbp.ma,"Exceptionally time consuming,time spent "+gap+"ms"+"\n it is from File.listFile() method",0);
                    toast.show();
                }
                //log.time("File.listFiles()");
				fbp.setWillShow(list);
                //log.time("fbp.setWillShow(list)");
			}
		}else{
			Toast.makeText(fbp.ma,t.dest.getAbsolutePath()+":不可读",0).show();
		}
	}

	@Override
	public boolean onLongClick(View view) {
		Tab tab=(Tab)view;
        MainActivity ma=fbp.ma;
        if(ma.qft==null)ma.qft=new QueryForTab(ma);
        ma.qft.show(this,tab);
		return true;
	}
	public class Tab extends TextView{
		File dest;
		Tab(File file){
			super(fbp.ma);
			setText(file.getName());
			setTypeface(Typeface.MONOSPACE);
			setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
			setGravity(Gravity.CENTER_VERTICAL);
			setOnClickListener(FileNavigator.this);
			setOnLongClickListener(FileNavigator.this);
			StateListDrawable sd=new StateListDrawable();
			sd.addState(new int[]{android.R.attr.state_pressed},new ColorDrawable(0x77888888));
			setBackground(sd);
			setPadding(10,0,10,0);
			if(file.canRead()){
				setTextColor(0xff000000);
			}else{
				setTextColor(0xffff0000);
			}
		}

		@Override
		protected void onDraw(Canvas canvas){
			super.onDraw(canvas);
			Paint p=new Paint();
			p.setStrokeWidth(3);
			p.setColor(0xff8297bb);
			int ii=getHeight()/8;
			canvas.drawLine(getWidth()-3,ii,getWidth()-3,getHeight()-ii,p);
		}

	}
    public static class QueryForTab extends LinearLayout implements OnClickListener{
        WindowManager.LayoutParams wlp=new WindowManager.LayoutParams();
        Tab destination;
        MainActivity ma;
        GUI.Item it0,it1,it2,it3,it4;
        QueryForTab(MainActivity ma){
            super(ma);
            this.ma=ma;
            setOrientation(1);
            setBackground(new GUI.BorderDrawable());
            it0=new GUI.Item(ma);
            it0.setText("重命名");
            it0.setOnClickListener(this);
            it1=new GUI.Item(ma);
            it1.setText("新标签中打开");
            it1.setOnClickListener(this);
            it2=new GUI.Item(ma);
            it2.setText("复制");
            it2.setOnClickListener(this);
            it3=new GUI.Item(ma);
            it3.setText("剪切");
            it3.setOnClickListener(this);
            it4=new GUI.Item(ma);
            it4.setText("详情");
            it4.setOnClickListener(this);
            LayoutParams itlp=new LayoutParams(-1,ma.dialogTitleBarHeight);
            addView(it0,itlp);
            addView(it1,itlp);
            addView(it2,itlp);
            addView(it3,itlp);
            addView(it4,itlp);
        }
        Tab tab;
        FileNavigator fn;
        void show(FileNavigator fn,Tab tab){
            this.tab=tab;
            this.fn=fn;
            wlp.width=ma.wp*2/3;
            wlp.height=-2;
            wlp.gravity=Gravity.LEFT|Gravity.TOP;
            wlp.flags=wlp.FLAG_LAYOUT_IN_SCREEN;
            Rect rect=new Rect();
            tab.getGlobalVisibleRect(rect);
            wlp.x=rect.left;
            wlp.y=rect.bottom;
            if(tab.dest.equals("/")){
                it0.setTextColor(0xff777777);
            }else if(tab.dest.canWrite()){
                it0.setTextColor(0xff000000);
            }else{
                it0.setTextColor(0xff777777);
            }
            if(tab.dest.canRead()){
                it1.setTextColor(0xff000000);
                it2.setTextColor(0xff000000);
                if(tab.dest.canWrite()){
                    it3.setTextColor(0xff000000);
                }else{
                    it3.setTextColor(0xff777777);
                }
            }else{
                it1.setTextColor(0xff777777);
                it2.setTextColor(0xff777777);
                it3.setTextColor(0xff777777);
            }
            ma.wm.addView(this,wlp);
        }
        @Override
        public void onClick(View v) {
            if(v==it0){
                if(tab.dest.equals("/")){
                    Toast.makeText(ma,"无法重命名根目录",0).show();
                }else if(tab.dest.canWrite()){
                    if(ma.qrt==null)ma.qrt=new QueryRename(ma);
                    ma.qrt.show(fn,tab);
                }
            }else if(v==it1){
                if(tab.dest.canRead()){
                    FileBrowserTab fbt=new FileBrowserTab(ma);
                    TabData.FileBrowserInfo fbi=new TabData.FileBrowserInfo();
                    fbi.home=tab.dest;
                    fbi.currentDir=tab.dest;
                    fbt.fbi=fbi;
                    fbt.setOnClickListener(ma.gui.TabOnClick);
                    fbt.setText(fbi.home.getName());
                    ma.gui.tabs.addView(fbt,TabBar.tablp);
                    ma.gui.TabOnClick.onClick(fbt);
                    ma.tabList.addTabInfo(fbt.fbi);
                    ma.tdm.updateSavedTabList(ma.tabList);
                }else{
                    Toast.makeText(ma,"不可读",0).show();
                }
            }else if(v==it2){
                File from=tab.dest;
                if(from.canRead()){
                    for(int index=0,len=ma.fileClipBoard.size();;index++){
                        if(index<len){
                            FileClipData fcd=ma.fileClipBoard.get(index);
                            if(fcd.f.equals(from)){
                                if(fcd.move){
                                    Toast.makeText(ma,"已存在此剪切",0).show();
                                }else{
                                    Toast.makeText(ma,"已存在此复制",0).show();
                                }
                                break;
                            }
                        }else{
                            FileClipData fcd=new FileClipData();
                            fcd.f=from;
                            fcd.move=false;
                            if(ma.fileClipBoard.add(fcd)){
                                ma.wm.removeView(this);
                                Toast.makeText(ma,"已复制",0).show();
                                fn.fbp.ivPaste.setVisibility(VISIBLE);
                            }
                            break;
                        }
                    }
                }else{
                    Toast.makeText(ma,"不可读",0).show();
                }
            }else if(v==it3){
                File from=tab.dest;
                if(from.canRead()){
                    if(from.canWrite()){
                        for(int index=0,len=ma.fileClipBoard.size();;index++){
                            if(index<len){
                                FileClipData fcd=ma.fileClipBoard.get(index);
                                if(fcd.f.equals(from)){
                                    if(fcd.move){
                                        Toast.makeText(ma,"已存在此剪切",0).show();
                                    }else{
                                        Toast.makeText(ma,"已存在此复制",0).show();
                                    }
                                   break; 
                                }
                            }else{
                                FileClipData fcd=new FileClipData();
                                fcd.f=from;
                                fcd.move=true;
                                ma.fileClipBoard.add(fcd);
                                ma.wm.removeView(this);
                                Toast.makeText(ma,"已剪切",0).show();
                                
                                fn.fbp.ivPaste.setVisibility(VISIBLE);
                                break;
                            }
                        }
                    }else{
                        Toast.makeText(ma,"不可写",0).show();
                    }
                }else{
                    Toast.makeText(ma,"不可读",0).show();
                }
            }else if(v==it4){
                if(ma.fileDetails==null)ma.fileDetails=new ShowFileDetails(ma);
                ma.fileDetails.show(tab.dest,fn.fbp);
            }
        }
        Point touchDown=new Point();
        @Override
        public boolean onTouchEvent(MotionEvent event){
            int x=(int)event.getX();
            int y=(int)event.getY();
            switch(event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    touchDown.x=x;
                    touchDown.y=y;
                    break;
                case MotionEvent.ACTION_UP:
                    Rect visible=new Rect();
                    getGlobalVisibleRect(visible);
                    if(touchDown.x>=visible.right||touchDown.x<visible.right||touchDown.y>=visible.bottom||touchDown.y<visible.top){
                        ma.wm.removeView(this);
                    }
            }
            super.onTouchEvent(event);
            return true;
        }
    }
    public static class QueryRename extends LinearLayout implements OnClickListener,TextWatcher,OnEditorActionListener{
        WindowManager.LayoutParams wlp=new WindowManager.LayoutParams();
        TextView sure;
        TextView title;
        IconViewClose close;
        ShowSoftInput ssi;
        LinearLayout titlebar;
        UnderlineSingleLineEditor editor;
        MainActivity ma;
        public QueryRename(MainActivity ma){
            super(ma);
            this.ma=ma;
            setOrientation(1);
            setBackground(new GUI.BorderDrawable());
            close=new IconViewClose(ma);
            close.setOnClickListener(this);
            title=new TextView(ma);
            title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
            title.setGravity(Gravity.CENTER_VERTICAL);
            title.setTextColor(0xff7f7f7f);
            title.setText("重命名目录");
            title.setPadding(9,0,0,0);
            ssi=new ShowSoftInput(ma);
            ssi.setOnClickListener(this);
            sure=new TextView(ma);
            sure.setText("确认");
            sure.setGravity(Gravity.CENTER);
            sure.setTextColor(0xff00ccff);
            sure.setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
            sure.setOnClickListener(this);
            titlebar=new LinearLayout(ma);
            titlebar.setOrientation(0);
            titlebar.setBackground(new GUI.BorderDrawable());
            titlebar.addView(title,new LayoutParams(0,-1,1f));
            titlebar.addView(ssi);
            titlebar.addView(close);
            editor=new UnderlineSingleLineEditor(ma);
            editor.setOnEditorActionListener(this);
            editor.addTextChangedListener(this);
            addView(titlebar,-1,ma.dialogTitleBarHeight);
            addView(editor,-1,(int)(33*ma.dp));
            addView(sure,-1,ma.dialogTitleBarHeight);
        }
        Tab dest;
        FileNavigator fn;
        public void show(FileNavigator fn,Tab dest){
            this.dest=dest;
            this.fn=fn;
            wlp.width=ma.wp*4/5;
            wlp.height=-2;
            String name=dest.dest.getName();
            editor.setText(name);
            ma.wm.addView(this,wlp);
        }
        @Override
        public void onClick(View v) {
            if(v==close){
                ma.wm.removeView(this);
            }else if(v==ssi){
                if(editor.requestFocus()){
                    ma.imm.showSoftInput(editor,0);
                    editor.selectAll();
                }
            }else if(v==sure){
                String usrinput=editor.getText().toString();
                if(usrinput.contains("/")){
                    Toast.makeText(ma,"无效的文件名",0).show();
                    return;
                }
                File newFile=new File(dest.dest.getParentFile(),usrinput);
                if(newFile.exists()){
                    if(newFile.equals(dest.dest)){
                        Toast.makeText(ma,"文件名未改变",0).show();
                        return;
                    }else{
                        Toast.makeText(ma,"文件已存在",0).show();
                    }
                }else if(dest.dest.renameTo(newFile)){
                    ma.wm.removeView(this);
                    Toast.makeText(ma,"重命名成功",0).show();
                    fn.fbp.currentDirectory=newFile;
                    fn.setPath(newFile);
                }else{
                    Toast.makeText(ma,"重命名失败",0).show();
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            String name=editor.getText().toString();
            File f=new File(dest.dest.getParentFile(),name);
            if(f.exists()){
                if(f.equals(dest.dest)){
                    Toast.makeText(ma,"文件名未改变",0).show();
                    return true;
                }else{
                    Toast.makeText(ma,"文件已存在",0).show();
                    return true;
                }
            }
            return false;
        }

                
    }
}
